/*
 * Copyright 2010-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jslet.paas.modelmeta.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.jslet.paas.modelmeta.model.ModelMeta;

@Repository("modelMetaDao")
public class ModelMetaDaoImpl implements ModelMetaDao
{
	private final static Logger logger = LoggerFactory.getLogger(ModelMetaDao.class);

	@PersistenceContext
	private EntityManager em;

	@SuppressWarnings("unchecked") 
	public List<ModelMeta> findAll()
	{
		Query query = em.createQuery("select p.modelId,p.name, p.fields from BizModel p");
		List<ModelMeta> result = (List<ModelMeta>)query.getResultList();
		return result;
	}
	
	public void createMetaModel(List<ModelMeta> newData)
	{
		if (newData == null || newData.size() == 0)
		{
			logger.warn("Empty list to create!");
			return;
		}
		for (ModelMeta entity : newData)
		{
			this.em.persist(entity);
		}
	}

	public void updateMetaModel(List<ModelMeta> updateData)
	{
		ModelMeta savingEnt;
		for(ModelMeta entity: updateData){
			savingEnt = this.em.find(ModelMeta.class, entity.getModelId());
			savingEnt.copyFrom(entity);
		    this.em.merge(savingEnt);
		}
	}

	public void deleteMetaModel(List<ModelMeta> deleteData)
	{
		if (deleteData == null || deleteData.size() == 0)
		{
			logger.warn("Empty list to delete!");
			return;
		}
		StringBuilder sb = new StringBuilder(60);
		sb.append("delete from BizModel p where p.bomId=?1");
		Query query = em.createQuery(sb.toString());
		for (ModelMeta entity : deleteData)
		{
			query.setParameter(1, entity.getModelId());
			query.executeUpdate();
		}
	}

}
